package com.xiaoqiudong.forum.controller;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import com.xiaoqiudong.forum.config.AppConfig;
import com.xiaoqiudong.forum.model.Message;
import com.xiaoqiudong.forum.model.User;
import com.xiaoqiudong.forum.service.IMessageService;
import com.xiaoqiudong.forum.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-29
 * Time:10:10
 */
@Slf4j
@Tag(name = "站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;

    @Operation(description = "发送站内信")
    @PostMapping("send")
    public AppResult send(HttpServletRequest request,
                          @Parameter(name = "receiveUserId",description = "接收者Id") @RequestParam("receiveUserId") @Nonnull Long receiveUserId,
                          @Parameter(name = "content",description = "信息内容") @RequestParam("content") @Nonnull String content){
        //获取当前登录用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验发送者
        if (user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //不能给自己发消息
        if (user.getId() == receiveUserId){
            log.warn("不能给自己发消息");
            return AppResult.fail("不能给自己发消息");
        }
        //校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.fail("接受者状态异常");
        }
        //封装对象，调用service
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        messageService.create(message);
        return AppResult.success();
    }

    @Operation(description = "获取未读消息数")
    @GetMapping("getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }


    @Operation(description = "获取消息列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);
    }

    @Operation(description = "更新为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(name = "id",description = "站内信id") @RequestParam("id") @Nonnull Long id){
        //根据id 查询站内信是否存在
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1){
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXIST);
        }
        //站内信是不是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId() != message.getReceiveUserId()){
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }
        messageService.updateStateById(id,(byte) 1);
        return AppResult.success();
    }


    @Operation(description = "回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @Parameter(name = "repliedId" ,description = "要回复站内信的Id")  @RequestParam("repliedId") @Nonnull Long repliedId,
                           @Parameter(name = "content" ,description = "回复类容")  @RequestParam("content") @Nonnull String content){

        //检查用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //检查站内信的状态
        Message exitsMessage = messageService.selectById(repliedId);
        if (exitsMessage == null || exitsMessage.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXIST.toString());
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXIST);
        }
        //检查要回回复的信是否是自己收到的
        if (user.getId() != exitsMessage.getReceiveUserId()){
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }
        //不能给自己发消息
        if(user.getId() == exitsMessage.getPostUserId()) {
            log.warn("不能给自己发送消息");
            return AppResult.fail("不能给自己发送消息");
        }
        //构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(exitsMessage.getPostUserId());
        message.setContent(content);

        //调用service
        messageService.reply(repliedId,message);
        return AppResult.success();
    }


}
